import React, { useState } from "react";
import { cn } from "~/components/lib/utils";
import VulnerabilityCommandTable, {
  type VulnTableItem,
} from "~/components/VulnerabilityCommandTable";
import { Button } from "~/components/lib/ui/button";
import { ViewModeSelector } from "~/components/ViewModeSelector";

// Type definition for view mode
export type ViewMode = "table" | "command" | "grouped";

// Interface for any vulnerability item that can be displayed in tables
export interface VulnerabilityViewItem {
  id: string; // Unique identifier (could be cve, vid, etc.)
  title?: string; // Title or name of the vulnerability
  description: string; // Description text
  severity: string; // Severity level
  riskScore: number; // Risk score (CVSS or equivalent)
  affectedHosts?: string[] | number; // Hosts affected (either list or count)
  published?: string; // Publication date
  lastModified?: string; // Last modified date
  references?: string[]; // Reference links
  [key: string]: any; // Allow for additional properties
}

// Common props for all vulnerability view components
interface VulnerabilityViewProps {
  data: VulnerabilityViewItem[];
  selectedItems?: string[];
  onSelectItems?: (ids: string[]) => void;
  onViewDetails?: (id: string) => void;
  isLoading?: boolean;
  viewMode: ViewMode;
}

// Convert generic vulnerability items to the specific format needed by VulnerabilityCommandTable
const convertToCommandTableFormat = (
  items: VulnerabilityViewItem[]
): VulnTableItem[] => {
  return items.map((item) => ({
    cve: item.id,
    severity: item.severity as any,
    description: item.description,
    riskScore: item.riskScore,
    affectedHosts: Array.isArray(item.affectedHosts)
      ? item.affectedHosts
      : typeof item.affectedHosts === "number"
      ? Array(item.affectedHosts).fill("")
      : [],
    published: item.published || "",
    lastModified: item.lastModified,
    references: item.references,
    selected: false,
  }));
};

// Main vulnerability view component that handles different view modes
export const VulnerabilityView: React.FC<VulnerabilityViewProps> = ({
  data,
  selectedItems = [],
  onSelectItems,
  onViewDetails,
  isLoading = false,
  viewMode,
}) => {
  // Convert data to the format needed by the specific view components
  const commandTableData = convertToCommandTableFormat(data);

  // Handle row selection
  const handleSelectRows = (ids: string[]) => {
    if (onSelectItems) {
      onSelectItems(ids);
    }
  };

  // Handle view details request
  const handleViewDetails = (id: string) => {
    if (onViewDetails) {
      onViewDetails(id);
    }
  };

  // Render the appropriate view based on viewMode
  switch (viewMode) {
    case "command":
      return (
        <VulnerabilityCommandTable
          data={commandTableData}
          onSelectRow={handleSelectRows}
          onViewDetails={handleViewDetails}
          selectedRows={selectedItems}
          isLoading={isLoading}
        />
      );
    case "table":
      // Placeholder for standard table view - to be implemented
      return (
        <div className="p-4 text-center">
          <p>Standard table view is not implemented yet.</p>
          <p className="text-sm text-gray-500">
            Please use Command Table view for now.
          </p>
        </div>
      );
    case "grouped":
      // Placeholder for grouped view - to be implemented
      return (
        <div className="p-4 text-center">
          <p>Grouped view is not implemented yet.</p>
          <p className="text-sm text-gray-500">
            Please use Command Table view for now.
          </p>
        </div>
      );
    default:
      return null;
  }
};

// Complete vulnerability table component with view selector and main view
export const VulnerabilityTableWithViewSelector: React.FC<
  Omit<VulnerabilityViewProps, "viewMode"> & {
    initialViewMode?: ViewMode;
    className?: string;
  }
> = ({
  data,
  selectedItems,
  onSelectItems,
  onViewDetails,
  isLoading,
  initialViewMode = "command",
  className,
}) => {
  const [viewMode, setViewMode] = useState<ViewMode>(initialViewMode);

  return (
    <div className={cn("flex flex-col", className)}>
      <div className="mb-4">
        <ViewModeSelector viewMode={viewMode} onViewChange={setViewMode} />
      </div>
      <div className="flex-grow">
        <VulnerabilityView
          data={data}
          selectedItems={selectedItems}
          onSelectItems={onSelectItems}
          onViewDetails={onViewDetails}
          isLoading={isLoading}
          viewMode={viewMode}
        />
      </div>
    </div>
  );
};

export default VulnerabilityView;
